﻿using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Linq;
using Kangaroo.DAL;
using Kangaroo.Model;
using Microsoft.Office.Interop.Excel;
using Action = System.Action;
using Font = System.Drawing.Font;
using Kangaroo.Configuration;

namespace Kangaroo.Shell
{
    public partial class DataWindow : Form
    {
        private readonly ChannelInfo _channel;
        private DataGridViewPrinter _myDataGridViewPrinter;

        public DataWindow(ChannelInfo channel)
        {
            _channel = channel;
            InitializeComponent();
            filterGroup.Text = Resource.DataWindow_DataWindow_QueryConditions;
            queryButton.Text = Resource.DataWindow_DataWindow_Query;
            startTimeLabel.Text = Resource.DataWindow_DataWindow_StartDate;
            endTimeLabel.Text = Resource.DataWindow_DataWindow_EndDate;

            Text = Resource.DataWindow_DataWindow_Title;

            exportToolStripButton.Text = Resource.DataWindow_DataWindow_ExportButtonText;
            printToolStripButton.Text = Resource.DataWindow_DataWindow_PrintButtonText;

            infoGroup.Text = Resource.DataWindow_DataWindow_SelectedChannel;
            devIdLabel.Text = Resource.DataWindow_DataWindow_DevIdLabel;
            devChnLabel.Text = Resource.DataWindow_DataWindow_DevChnLabel;
            equipIdLabel.Text = Resource.DataWindow_DataWindow_EquipIdLabel;
            equipPhaseLabel.Text = Resource.DataWindow_DataWindow_EquipPhaseLabel;

            devIdBox.Text = channel.DevId;
            devChnBox.Text = channel.DevChn.ToString();
            equipIdBox.Text = channel.EquipId;
            equipPhaseBox.Text = channel.EquipPhase.ToString();
        }

        private void DataWindow_Load(object sender, EventArgs e)
        {
            startDateTimePicker.Value = DateTime.Now.AddDays(-7);
            endDateTimePicker.Value = DateTime.Now;
        }

        private void queryButton_Click(object sender, EventArgs e)
        {
            var signalData = Data.Signal;
            signalData.ListSignalsByChannelWithinTimeAsync(
                _channel.Key, startDateTimePicker.Value, endDateTimePicker.Value.AddDays(1)).Then(
                    signalsTable => BeginInvoke((Action)delegate
                    {
                        pdBindingSource.DataSource = signalsTable;
                        pdDataGridView.DataSource = pdBindingSource;
                        for (int i = 0; i < pdDataGridView.ColumnCount; i++)
                        {
                            Config.DataDetailName name = Config.Instance.DataDetailNames.FirstOrDefault(d => d.Id == pdDataGridView.Columns[i].DataPropertyName);
                            if (name == null)
                            {
                                pdDataGridView.Columns[i].Visible = false;
                            }
                            else
                            {
                                pdDataGridView.Columns[i].Visible = true;
                                pdDataGridView.Columns[i].HeaderText = name.Name;
                            }
                        }
                            pdDataGridView.AutoResizeColumns(
                                DataGridViewAutoSizeColumnsMode.DisplayedCells);
                    }),
                    exception => BeginInvoke((Action)(() => MessageBox.Show(exception.Message))));
        }

        private void startDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            if(IsTimeSelectionConflict())
            {
                endDateTimePicker.Value = startDateTimePicker.Value;
            }
        }

        private void endDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            if(IsTimeSelectionConflict())
            {
                startDateTimePicker.Value = endDateTimePicker.Value;
            }
        }

        private bool IsTimeSelectionConflict()
        {
            return endDateTimePicker.Value < startDateTimePicker.Value;
        }

        private void exportToolStripButton_Click(object sender, EventArgs e)
        {
            using(var saveFileDialog = new SaveFileDialog())
            {
                saveFileDialog.Filter = Resource.DataWindow_exportToolStripButton_Click_Excel_FileFilter;
                saveFileDialog.RestoreDirectory = true;
                if(saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //获得文件路径    
                    var localFilePath = saveFileDialog.FileName;

                    var excelApp = new ApplicationClass();
                    excelApp.Application.Workbooks.Add(Type.Missing);
                    excelApp.Columns.ColumnWidth = 30;
                    for(var i = 0; i < pdDataGridView.Rows.Count - 1; i++)
                    {
                        var row = pdDataGridView.Rows[i];
                        for(var j = 0; j < row.Cells.Count; j++)
                        {
                            excelApp.Cells[i + 1, j + 1] = row.Cells[j].Value.ToString();
                        }
                    }
                    excelApp.ActiveWorkbook.SaveCopyAs(localFilePath);
                    excelApp.ActiveWorkbook.Saved = true;
                    excelApp.Quit();
                }
            }
        }

        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            if(SetupThePrinting())
                MyPrintDocument.Print();
        }

        private void previewToolStripButton_Click(object sender, EventArgs e)
        {
            if(SetupThePrinting())
            {
                var myPrintPreviewDialog = new PrintPreviewDialog { Document = MyPrintDocument };
                myPrintPreviewDialog.ShowDialog();
            }
        }

        private bool SetupThePrinting()
        {
            var myPrintDialog = new PrintDialog
            {
                AllowCurrentPage = false,
                AllowPrintToFile = false,
                AllowSelection = false,
                AllowSomePages = false,
                PrintToFile = false,
                ShowHelp = false,
                ShowNetwork = false
            };

            if(myPrintDialog.ShowDialog() != DialogResult.OK)
                return false;

            MyPrintDocument.DocumentName = Resource.DataWindow_SetupThePrinting_PrintDocName;
            MyPrintDocument.PrinterSettings = myPrintDialog.PrinterSettings;
            MyPrintDocument.DefaultPageSettings = myPrintDialog.PrinterSettings.DefaultPageSettings;
            MyPrintDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);

            _myDataGridViewPrinter = new DataGridViewPrinter(pdDataGridView, MyPrintDocument, 
                true, true, Resource.DataWindow_SetupThePrinting_PrintTitle,
                new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

            return true;
        }

        private void MyPrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            var more = _myDataGridViewPrinter.DrawDataGridView(e.Graphics);
            if(more)
                e.HasMorePages = true;
        }
    }
}